# -*- coding=UTF-8 -*-
# @Project          WeChatPublicNumberPushInformation
# @fileName         wechat_push_message.py
# @author           Echo
# @EditTime         2024/9/10
import datetime
import random
import time
from typing import *

import httpx

from common import config
from common.tian_api import TianApi
from utils.date_time_tools.time_calculation import calculate_birthday, claculate_love_date, claculate_exam_countdown


class WeChatPushMessage:
    def __init__(self):
        self.client = httpx.Client()
        self.tian_api = TianApi()

    @staticmethod
    def get_color():
        # 获取随机颜色
        get_colors = lambda n: list(map(lambda i: "#" + "%06x" % random.randint(0, 0xFFFFFF), range(n)))
        color_list = get_colors(100)
        return random.choice(color_list)

    def send_email(self, subject, contents):
        """
        发送邮件
        :param subject: 邮件主题
        :param message: 邮件内容
        :return: 
        """
        import yagmail
        # 配置
        sender_name = "微信消息推送"
        sender_email = "liulong3men@163.com"
        sender_password = "XUJFCMOZOXZUWMTT"
        receiver_email = "1873190160@qq.com"

        # 发送邮件
        try:
            # 创建 yagmail 客户端
            yag = yagmail.SMTP({sender_email: sender_name}, password=sender_password, host="smtp.163.com", port=465)

            # 发送邮件
            yag.send(
                to=receiver_email,
                subject=subject,
                contents=contents
            )
            print("邮件发送成功！")
        except Exception as e:
            print(f"邮件发送失败：{str(e)}")

    @staticmethod
    def split_str(str_: Text, length: int = 20):
        chunks = [str_[i:i + length] for i in range(0, len(str_), length)]
        result = {}
        for i, chunk in enumerate(chunks, 1):
            var_name = f"content_{i}"
            result[var_name] = chunk
        return result

    def __get_access_token(self) -> Text:
        appid = config.get("appid")
        appsecret = config.get("appsecret")
        url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}"
        try:
            response = self.client.get(url).json()
            return response["access_token"]
        except KeyError:
            raise KeyError("获取access_token失败！检查appid和appsecret是否正确.")

    def push_message(self, user):
        # city = config.get("cityName") + config.get("area")
        week_list = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
        time_ = time.strftime('%Y年%m月%d日 %H:%M:%S（' + week_list[datetime.date.today().isoweekday() % 7] + '）',
                              time.localtime((int(time.mktime(time.gmtime())) + 28800)))  # 获取当前时间
        birthday = calculate_birthday(config.get("birthday"))  # 计算生日
        love_date = claculate_love_date(config.get("love_date"))  # 计算恋爱日
        exam_date = claculate_exam_countdown(config.get("examination_date"))  # 计算考研剩余时间
        weather_info = self.tian_api.get_weather_infos(config.get("area"))
        weather_condition = weather_info.get("weather")  # 天气状况
        max_temperature = weather_info.get("highest")  # 最高温度
        current_temperature = weather_info.get("real")  # 实时温度
        min_temperature = weather_info.get("lowest")  # 最低温度

        star_sign = config.get("starSign")  # 星座
        star_sign_info = self.tian_api.get_horoscope(star_sign)
        composite_index = star_sign_info[0]["content"]  # 综合指数
        love_index = star_sign_info[1]["content"]  # 恋爱指数
        work_index = star_sign_info[2]["content"]  # 工作指数
        fortune_index = star_sign_info[3]["content"]  # 财运指数
        health_index = star_sign_info[4]["content"]  # 健康指数
        speed_sign = star_sign_info[7]["content"]  # 速配星座

        url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={self.__get_access_token()}"
        messages = {

            "touser": user,
            "template_id": config.get("templateId"),
            "url": "http://www.baidu.com",
            "topcolor": "#FF0000",
            "data": {
                "today": {"value": time_, "color": self.get_color()},  # 当前时间
                "ld": {"value": love_date, "color": "#EC2417"},  # 恋爱日
                # "city": {"value": city, "color": self.get_color()},    # 城市
                "w": {"value": weather_condition, "color": self.get_color()},  # 天气状况
                "c_temp": {"value": current_temperature, "color": self.get_color()},  # 实时温度
                "min_temp": {"value": min_temperature, "color": self.get_color()},  # 最低温度
                "max_temp": {"value": max_temperature, "color": self.get_color()},  # 最高温度
                "u": {"value": config.get("user"), "color": self.get_color()},  # 用户
                "b": {"value": birthday, "color": self.get_color()},  # 生日
                "exa_day": {"value": exam_date, "color": self.get_color()},  # 考研剩余时间
                # "c_i": {"value": composite_index, "color": self.get_color()},    # 综合指数
                "l_i": {"value": love_index, "color": self.get_color()},  # 恋爱指数
                "w_i": {"value": work_index, "color": self.get_color()},  # 工作指数
                "f_i": {"value": fortune_index, "color": self.get_color()}  # 财运指数
                # "h_i": {"value": health_index, "color": self.get_color()},  # 健康指数
                # "s_s": {"value": speed_sign, "color": self.get_color()},  # 速配星座
            }
        }
        # tips_info = weather_info.get("tips")  # 出行建议
        # split_tips = self.split_str(tips_info)
        # tips_fields = ["tips1", "tips2", "tips3", "tips4", "tips5"]
        # for i, field in enumerate(tips_fields, 1):
        #     if f"content_{i}" in split_tips:
        #         messages["data"][field] = {"value": split_tips[f"content_{i}"], "color": self.get_color()}

        today_summarize_info = star_sign_info[8]["content"]  # 今日运势
        split_today_summarize_info = self.split_str(today_summarize_info)
        today_summarize_fields = ["sign1", "sign2", "sign3", "sign4", "sign5"]
        for i, field in enumerate(today_summarize_fields, 1):
            if f"content_{i}" in split_today_summarize_info:
                messages["data"][field] = {"value": split_today_summarize_info[f"content_{i}"],
                                           "color": self.get_color()}

        rainbow_fart_info = self.tian_api.get_rainbowFart()
        if "XXX" in rainbow_fart_info:
            rainbow_fart_info = rainbow_fart_info.replace("XXX", config.get("user"))
        split_rainbow_fart_info = self.split_str(rainbow_fart_info)
        rainbow_fart_fields = ["copy1", "copy2", "copy3", "copy4", "copy5"]
        for i, field in enumerate(rainbow_fart_fields, 1):
            if f"content_{i}" in split_rainbow_fart_info:
                messages["data"][field] = {"value": split_rainbow_fart_info[f"content_{i}"], "color": self.get_color()}
        try:
            response = self.client.post(url, json=messages).json()
            if response.get("errcode") == 0 and response.get("errmsg") == "ok":
                print("推送成功")
                self.send_email(subject=f"🗨️微信公众号通知 - {datetime.datetime.now().strftime("%Y/%m/%d")}",
                                contents=f"⏰向【{config.get('user')}】早安信息已成功推送啦！")
            else:
                print("推送失败", response)
                self.send_email(subject=f"🗨️微信公众号通知 - {datetime.datetime.now().strftime("%Y/%m/%d")}",
                                contents=f"❌向【{config.get('user')}】早安信息推送失败，请前往青龙面板查看日志！")

        except KeyError:
            raise KeyError("推送失败，请检查参数是否正确")


if __name__ == '__main__':
    users = config.get("wechatUserId")
    for user in users:
        wpm = WeChatPushMessage()
        wpm.push_message(user)
        del wpm
